package net.butfly.albacore.dbo.interceptor;

import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.session.RowBounds;

public abstract class PaginationInterceptor extends AbstractInterceptor {

	@Override
	public final Object intercept(Invocation invocation) throws Throwable {
		StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
		MetaObject metaStatementHandler = MetaObject.forObject(statementHandler);
		RowBounds rowBounds = (RowBounds) metaStatementHandler.getValue("delegate.rowBounds");
		if (rowBounds != null && rowBounds.getOffset() != RowBounds.NO_ROW_OFFSET) {
			String originalSql = (String) metaStatementHandler.getValue("delegate.boundSql.sql");
			metaStatementHandler.setValue("delegate.boundSql.sql", 
					this.pagination(originalSql, rowBounds.getOffset(), rowBounds.getLimit()));
			metaStatementHandler.setValue("delegate.rowBounds.offset", RowBounds.NO_ROW_OFFSET);
			metaStatementHandler.setValue("delegate.rowBounds.limit", RowBounds.NO_ROW_LIMIT);
			logger.debug("page sql generated: " + statementHandler.getBoundSql().getSql());
		}
		return invocation.proceed();
	}

	abstract protected String pagination(String sql, int offset, int limit);
}
